<template>
  <div class="card bg-light-50 rounded w-500px h-500px p-20px box-border">
    <div class="text-center text-xl">欢迎登录</div>
    <div class="mt-30px flex flex-col items-center">
      <div class="w-2/3">
        <n-input v-model:value="mobile" placeholder="请输入手机号"/>
      </div>
      <div class="w-2/3 mt-10px">
        <n-input v-model:value="password" type="password" placeholder="请输入密码"/>
      </div>
      <div class="w-2/3 mt-10px between~">
        <div class="flex-1">
          <n-input v-model:value="code" placeholder="请输入验证码"/>
        </div>
        <div class="text-center ml-5px">
          <image-code :pic-path="picPath" @click="getCode"/>
        </div>
      </div>
      <div class="w-2/3 mt-10px">
        <n-button class="w-full" @click="onLogin" type="info">登录</n-button>
      </div>
      <div class="text-xs mt-10px">
        <span>还没有账号？</span>
        <span class="text-blue-500 cursor-pointer" @click="onCheck">
          去注册
        </span>
      </div>
    </div>
  </div>
</template>

<script lang="ts">
import {defineComponent, ref} from "vue";
import ImageCode from "@/components/viewComponents/ImageCode.vue";
import {NButton, NInput, useMessage} from "naive-ui"
import {useCaptcha, usePost} from "@/hooks";
import router from "@/router";
import {setToken} from "@/util";
import {useInitLogin} from "@/pages/userLogin/hooks";

export default defineComponent({
  components: {ImageCode, NButton, NInput},
  emits: ["check"],
  setup(props, {emit}) {
    const {mobile, password, checkStatus, code} = useInitLogin()
    const message = useMessage()
    const viewReady = ref(true);
    const {picPath, picId, getCode} = useCaptcha();

    async function onLogin() {
      const text = checkStatus()
      if (text) {
        message.error(text)
        return
      }

      await usePost({
        url: "/v1/user/pwd_login",
        data: {
          mobile: mobile.value,
          password: password.value,
          captcha: code.value,
          captcha_id: picId.value,
        },
        success: (data) => {
          setToken(data.token);
          router.push("/workspace");
        },
        fail: () => {
          message.error("登录错误")
        },
      });
    }

    function onCheck() {
      emit("check")
    }

    return {
      picPath,
      picId,
      getCode,
      onLogin,
      viewReady,
      mobile,
      password,
      code,
      onCheck
    }
  }
})


</script>

<style scoped>
.card {
  box-shadow: 0 0 5px var(--gray);
}
</style>
